package com.fiberhome.opticalbox.ui.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;

import com.fiberhome.opticalbox.R;
import com.fiberhome.opticalbox.BaseFragment;
import com.fiberhome.opticalbox.net.NetConstant;
import com.fiberhome.opticalbox.net.NetManager.TcpErrorListener;
import com.fiberhome.opticalbox.net.NetManager.TcpListener;
import com.fiberhome.opticalbox.net.bean.Parameter;
import com.fiberhome.opticalbox.net.utils.JsonUtil;
import com.fiberhome.opticalbox.ui.MainActivity;
import com.fiberhome.opticalbox.ui.ProductListActivity;
import com.fiberhome.opticalbox.utils.AnimUtil;

public class WifiCtrlMasterFragment extends BaseFragment {

	private MainActivity holder;

	private CheckBox ckWifiAble, ckPasswordAble;
	private EditText edName, edPassword;
	private CheckBox ckPasswordShow;
	private Button btnSave;
	private View layPassword;
	private View layPasswordShow;
	private View layWrapName, layWrapPwd;
	private ImageView imgIcoName, imgIcoPwd;

	private Dialog dlgWifiCtrl, dlgLoading;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity instanceof MainActivity) {
			holder = (MainActivity) activity;
		}
		registerChildTcpListener(tcpListener);
		registerChildTcpErrorListener(tcpErrorListener);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.ob_fragment_wifi_ctrl_master, null);

		ckWifiAble = (CheckBox) view.findViewById(R.id.ck_wifi_able);
		ckPasswordAble = (CheckBox) view.findViewById(R.id.ck_password_able);
		edName = (EditText) view.findViewById(R.id.ed_name);
		edPassword = (EditText) view.findViewById(R.id.ed_pwd);
		ckPasswordShow = (CheckBox) view.findViewById(R.id.ck_password_show);
		btnSave = (Button) view.findViewById(R.id.btn_save);
		layPassword = view.findViewById(R.id.lay_password);

		ckWifiAble.setOnCheckedChangeListener(wifiAbleListener);
		ckPasswordAble.setOnCheckedChangeListener(passwordAbleListener);
		btnSave.setOnClickListener(onSaveListener);
		ckPasswordShow.setOnCheckedChangeListener(passwordShowListener);
		layPasswordShow = view.findViewById(R.id.lay_password_show);
		layPasswordShow.setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				ckPasswordShow.performClick();
			}
		});

		layWrapName = view.findViewById(R.id.lay_wrap_name);
		layWrapPwd = view.findViewById(R.id.lay_wrap_pwd);
		imgIcoName = (ImageView) view.findViewById(R.id.img_ico_name);
		imgIcoPwd = (ImageView) view.findViewById(R.id.img_ico_pwd);
		edName.setOnFocusChangeListener(onEditTextFocusChangeListener);
		edPassword.setOnFocusChangeListener(onEditTextFocusChangeListener);

		requestGetWifiInfo();
		return view;
	}

	private OnCheckedChangeListener wifiAbleListener = new OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(CompoundButton arg0, boolean checked) {
			// do nothing
		}
	};

	private OnCheckedChangeListener passwordAbleListener = new OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(CompoundButton arg0, boolean checked) {
			if (checked) {
				holder.startAnimation(layPassword, AnimUtil.init().addAlpha(0f, 1f).create());
			} else {
				holder.endAnimation(layPassword, AnimUtil.init().addAlpha(1f, 0f).create());
			}
		}
	};

	private OnCheckedChangeListener passwordShowListener = new OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(CompoundButton arg0, boolean checked) {
			edPassword.setInputType(checked ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
					: (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD));
			edPassword.setSelection(edPassword.getText().length());
		}
	};

	private OnClickListener onSaveListener = new OnClickListener() {
		@Override
		public void onClick(View view) {
			if (validateRequestSetWifiInfo()) {
				showSetWifiCtrlDialog();
			}
		}
	};

	private boolean validateRequestSetWifiInfo() {
		String inputPassword = edPassword.getText().toString().trim();
		if (inputPassword.length() < 8 && ckPasswordAble.isChecked()) {
			showToast(R.string.ob_password_short_1);
			return false;
		}
		return true;
	}

	private OnFocusChangeListener onEditTextFocusChangeListener = new OnFocusChangeListener() {
		@Override
		public void onFocusChange(View view, boolean hasFocus) {
			int background = hasFocus ? R.drawable.ob_border_n_ff00aef1 : R.drawable.ob_border_n_ffe1e1e1;
			switch (view.getId()) {
			case R.id.ed_name:
				layWrapName.setBackgroundResource(background);
				imgIcoName.setImageResource(hasFocus ? R.drawable.ob_edit_user_pressed : R.drawable.ob_edit_user_normal);
				break;
			case R.id.ed_pwd:
				layWrapPwd.setBackgroundResource(background);
				imgIcoPwd.setImageResource(hasFocus ? R.drawable.ob_edit_password_pressed : R.drawable.ob_edit_password_normal);
				break;
			}
		}
	};

	private void requestGetWifiInfo() {
		if (netManager != null) {
			String WifiIndex = "1"; //
			String SSIDIndex = "1"; // 私人"1",共有"2"
			netManager.sendTcp(JsonUtil.get_GET_WIFI_INFO(WifiIndex, SSIDIndex));
		}
	}

	private void requestSetWifiInfo() {
		if (netManager != null) {
			String WifiIndex = "1"; //
			String PowerLevel = "100"; // 此SSID的网络功耗（百分比表示，取值0-100）
			String Channel = "0"; // 0表示Auto
			String WifiCmdMode = "0"; /* 0表示设置AP相关操作，1表示对关联其他AP动作 */
			String SSIDIndex = "1"; // 私人
			String SSID = edName.getText().toString().trim();
			String PWD = edPassword.getText().toString().trim();
			String ENCRYPT = ckPasswordAble.isChecked() ? "4" : "1"; // OPEN=1,SHARED=2,WPA-PSK=3,WPA-PSK2=4,MixdWPA2/WPA-PSK=5
			String Enable = ckWifiAble.isChecked() ? "1" : "0"; // 1表示启用，0表示不启用
			String Hidden = "";
			netManager.sendTcp(JsonUtil.get_SET_WIFI_INFO(WifiIndex, SSIDIndex, SSID, PWD, ENCRYPT, PowerLevel, Channel, Enable,
					WifiCmdMode, Hidden));
		}
	}

	private TcpListener tcpListener = new TcpListener() {
		@Override
		public void onReceive(String cmdType, Parameter param) {
			if (NetConstant.GET_WIFI_INFO.equals(cmdType)) {
				if ("1".equals(param.SSIDIndex)) {
					edName.setText(param.SSID);
					edPassword.setText(param.PWD);
					ckPasswordAble.setChecked(!"1".equals(param.ENCRYPT));
					ckWifiAble.setChecked("1".equals(param.Enable));
				}
			} else if (NetConstant.SET_WIFI_INFO.equals(cmdType)) {
				showToast(R.string.ob_success_set_wifi_ctrl_1);
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						if (dlgLoading != null) {
							dlgLoading.dismiss();
						}

						actionStart(ProductListActivity.class);
						finishAttachActivity();
					}
				}, 20000);
			}
		}
	};

	private TcpErrorListener tcpErrorListener = new TcpErrorListener() {
		@Override
		public void onError(String cmdType) {
			if (NetConstant.GET_WIFI_INFO.equals(cmdType)) {
				// no nothing
			} else if (NetConstant.SET_WIFI_INFO.equals(cmdType)) {
				showToast(R.string.ob_fail_set_wifi_info);
			}
		}
	};

	private void showSetWifiCtrlDialog() {
		dlgWifiCtrl = dialogUtil.createSimple(R.string.ob_dlg_wifi_ctrl_reset, true, true).setConfirmListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dlgWifiCtrl.dismiss();
				showLoadingDialog();
				requestSetWifiInfo();
			}
		}).show();
	}

	private void showLoadingDialog() {
		dlgLoading = dialogUtil.createLoading(R.string.ob_wait_set_wifi_mode_1, false, true).show();
	}
}
